package cn.iocoder.yudao.module.cmt.service.content;

import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
import cn.iocoder.yudao.module.cmt.controller.admin.content.vo.*;
import cn.iocoder.yudao.module.cmt.dal.dataobject.content.ContentCommentDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.cmt.dal.mysql.content.ContentCommentMapper;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.cmt.enums.ErrorCodeConstants.*;

@Service
@Validated
public class ContentCommentServiceImpl implements ContentCommentService {

    @Resource
    private ContentCommentMapper contentCommentMapper;

    @Override
    public Long createComment(ContentCommentSaveReqVO createReqVO) {
        ContentCommentDO comment = BeanUtils.toBean(createReqVO, ContentCommentDO.class);
        contentCommentMapper.insert(comment);
        return comment.getId();
    }

    @Override
    public void updateComment(ContentCommentSaveReqVO updateReqVO) {
        validateCommentExists(updateReqVO.getId());
        ContentCommentDO updateObj = BeanUtils.toBean(updateReqVO, ContentCommentDO.class);
        contentCommentMapper.updateById(updateObj);
    }

    @Override
    public void deleteComment(Long id) {
        validateCommentExists(id);
        contentCommentMapper.deleteById(id);
    }

    private void validateCommentExists(Long id) {
        if (contentCommentMapper.selectById(id) == null) {
            throw exception(COMMENT_NOT_EXISTS);
        }
    }

    @Override
    public ContentCommentDO getComment(Long id) {
        return contentCommentMapper.selectById(id);
    }

    @Override
    public PageResult<ContentCommentDO> getCommentPage(ContentCommentPageReqVO pageReqVO) {
        return contentCommentMapper.selectPage(pageReqVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteCommentListByIds(List<Long> ids) {
        ids.forEach(this::validateCommentExists);
        contentCommentMapper.deleteBatchIds(ids);
    }

}
